package Util;

import Entity.MsgAndEmail.Email;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class EmailUtil {


    /**
     * 发送一封简单的文本邮件
     *
     * @param email     发送邮件对象
     * @param emailCode 发送邮箱的16位授权码
     */
    public static Boolean sendEmail(Email email, String emailCode) {
        boolean flag = false;
        //创建一个配置文件并保存
        Properties properties = new Properties();
        properties.setProperty("mail.host", "smtp.qq.com"); //主机 stmp.qq.com
        properties.setProperty("mail.transport.protocol", "smtp"); //指定协议
        properties.setProperty("mail.smtp.auth", "true"); //用户密码认证
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //QQ存在一个特性设置SSL加密

        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(email.getSendEmail(), emailCode);
            }
        });
        //开启debug模式
        session.setDebug(true);

        //获取连接对象
        Transport transport = null;
        try {

            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(email.getSendEmail())); //邮件发送人
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email.getReceiveEmail())); //邮件接收人
            mimeMessage.setSubject(email.getTitle());  //邮件标题
            mimeMessage.setSentDate(new Date());  //邮件发送时间
            mimeMessage.setContent(email.getContent(), "text/html;charset=UTF-8");//邮件内容
            transport = session.getTransport();
            // mimeMessage.setText("正文");
            transport.connect(email.getSendEmail(), emailCode); //连接服务器
            //发送邮件
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            try {
                if (transport != null)
                    transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }


}
